import json
from datetime import datetime, timedelta
from django.http import JsonResponse
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Count, Q
from django.utils import timezone
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status

from user.models import SysUser
from role.models import SysRole
from .models import SystemLog, SystemMetrics, QuickAction
from user.permissions import get_user_role_names


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_dashboard_stats(request):
    """获取仪表板统计数据"""
    try:
        # 获取当前用户角色
        current_user = request.user
        user_roles = get_user_role_names(current_user.id)
        current_role = user_roles[0] if user_roles else '普通用户'
        
        # 根据角色过滤数据
        if current_role == '超级管理员':
            # 超级管理员可以看到所有数据
            total_users = SysUser.objects.filter(status=0).count()
            total_roles = SysRole.objects.count()
            total_logs = SystemLog.objects.count()
        elif current_role == '普通管理员':
            # 普通管理员只能看到普通用户数据
            total_users = SysUser.objects.filter(
                status=0,
                sysuserrole__role__name='普通用户'
            ).count()
            total_roles = SysRole.objects.filter(name__in=['普通用户']).count()
            total_logs = SystemLog.objects.filter(
                user__sysuserrole__role__name='普通用户'
            ).count()
        else:
            # 普通用户只能看到自己的数据
            total_users = 1  # 只有自己
            total_roles = 1   # 只有自己的角色
            total_logs = SystemLog.objects.filter(user=current_user).count()
        
        # 系统模块数量（固定值）
        total_modules = 12
        
        # 计算趋势（模拟数据）
        stats_data = [
            {
                'id': 1,
                'number': f'{total_users:,}',
                'label': '总用户数',
                'icon': 'User',
                'colorClass': 'stat-blue',
                'trend': '+12.5%',
                'trendIcon': 'CaretTop',
                'trendClass': 'trend-up'
            },
            {
                'id': 2,
                'number': str(total_roles),
                'label': '角色数量',
                'icon': 'Avatar',
                'colorClass': 'stat-green',
                'trend': '+3.2%',
                'trendIcon': 'CaretTop',
                'trendClass': 'trend-up'
            },
            {
                'id': 3,
                'number': str(total_modules),
                'label': '系统模块',
                'icon': 'Monitor',
                'colorClass': 'stat-orange',
                'trend': '0%',
                'trendIcon': 'CaretBottom',
                'trendClass': 'trend-stable'
            },
            {
                'id': 4,
                'number': f'{total_logs:,}',
                'label': '操作日志',
                'icon': 'Document',
                'colorClass': 'stat-purple',
                'trend': '+18.7%',
                'trendIcon': 'CaretTop',
                'trendClass': 'trend-up'
            }
        ]
        
        return Response({
            'code': 200,
            'message': '获取统计数据成功',
            'data': stats_data
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取统计数据失败: {str(e)}',
            'data': []
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_recent_activities(request):
    """获取最近活动数据"""
    try:
        current_user = request.user
        user_roles = get_user_role_names(current_user.id)
        current_role = user_roles[0] if user_roles else '普通用户'
        
        # 根据角色过滤活动数据
        if current_role == '超级管理员':
            # 超级管理员可以看到所有活动
            recent_logs = SystemLog.objects.select_related('user').order_by('-created_at')[:10]
        elif current_role == '普通管理员':
            # 普通管理员只能看到普通用户的活动
            recent_logs = SystemLog.objects.select_related('user').filter(
                user__sysuserrole__role__name='普通用户'
            ).order_by('-created_at')[:10]
        else:
            # 普通用户只能看到自己的活动
            recent_logs = SystemLog.objects.select_related('user').filter(
                user=current_user
            ).order_by('-created_at')[:10]
        
        activities = []
        for log in recent_logs:
            # 计算时间显示
            time_diff = timezone.now() - log.created_at
            if time_diff.days > 0:
                time_display = f'{time_diff.days}天前'
            elif time_diff.seconds > 3600:
                hours = time_diff.seconds // 3600
                time_display = f'{hours}小时前'
            elif time_diff.seconds > 60:
                minutes = time_diff.seconds // 60
                time_display = f'{minutes}分钟前'
            else:
                time_display = '刚刚'
            
            # 根据操作类型设置图标和样式
            icon_mapping = {
                'create': {'icon': 'User', 'typeClass': 'activity-primary'},
                'update': {'icon': 'Edit', 'typeClass': 'activity-warning'},
                'delete': {'icon': 'Delete', 'typeClass': 'activity-danger'},
                'login': {'icon': 'User', 'typeClass': 'activity-success'},
                'logout': {'icon': 'SwitchButton', 'typeClass': 'activity-info'},
                'view': {'icon': 'View', 'typeClass': 'activity-info'},
                'upload': {'icon': 'Upload', 'typeClass': 'activity-primary'},
                'download': {'icon': 'Download', 'typeClass': 'activity-primary'},
            }
            
            icon_info = icon_mapping.get(log.action, {'icon': 'User', 'typeClass': 'activity-info'})
            
            activities.append({
                'id': log.id,
                'content': log.content,
                'user': log.user.nickname if log.user.nickname else log.user.username,
                'timestamp': time_display,
                'icon': icon_info['icon'],
                'typeClass': icon_info['typeClass']
            })
        
        return Response({
            'code': 200,
            'message': '获取活动数据成功',
            'data': activities
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取活动数据失败: {str(e)}',
            'data': []
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_system_metrics(request):
    """获取系统性能指标"""
    try:
        # 尝试使用psutil获取实际系统指标
        try:
            import psutil
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            
            metrics = {
                'cpu_usage': round(cpu_percent, 1),
                'memory_usage': round(memory.percent, 1),
                'disk_usage': round(disk.percent, 1),
                'timestamp': timezone.now().isoformat()
            }
            
            # 保存到数据库（可选）
            SystemMetrics.objects.create(
                cpu_usage=cpu_percent,
                memory_usage=memory.percent,
                disk_usage=disk.percent
            )
            
            message = '获取系统指标成功'
            
        except ImportError:
            # 如果psutil不可用，返回模拟数据
            import random
            metrics = {
                'cpu_usage': round(random.uniform(20, 80), 1),
                'memory_usage': round(random.uniform(40, 85), 1),
                'disk_usage': round(random.uniform(30, 70), 1),
                'timestamp': timezone.now().isoformat()
            }
            message = '获取系统指标成功（模拟数据）'
        
        # 清理旧数据，只保留最近24小时的记录
        cutoff_time = timezone.now() - timedelta(hours=24)
        SystemMetrics.objects.filter(timestamp__lt=cutoff_time).delete()
        
        return Response({
            'code': 200,
            'message': message,
            'data': metrics
        })
        
    except Exception as e:
        # 如果出现任何错误，返回模拟数据
        import random
        metrics = {
            'cpu_usage': round(random.uniform(20, 80), 1),
            'memory_usage': round(random.uniform(40, 85), 1),
            'disk_usage': round(random.uniform(30, 70), 1),
            'timestamp': timezone.now().isoformat()
        }
        
        return Response({
            'code': 200,
            'message': f'获取系统指标成功（模拟数据）: {str(e)}',
            'data': metrics
        })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_quick_actions(request):
    """获取快速操作配置"""
    try:
        current_user = request.user
        user_roles = get_user_role_names(current_user.id)
        current_role = user_roles[0] if user_roles else '普通用户'
        
        # 根据角色过滤快速操作
        base_actions = [
            {
                'id': 1,
                'title': '添加用户',
                'description': '创建新用户账户',
                'icon': 'User',
                'colorClass': 'action-blue',
                'route': '/home/user/users_management',
                'permission': 'super_admin'
            },
            {
                'id': 2,
                'title': '角色管理',
                'description': '配置角色权限',
                'icon': 'Avatar',
                'colorClass': 'action-green',
                'route': '/home/user/roles_management',
                'permission': 'super_admin'
            },
            {
                'id': 3,
                'title': '个人中心',
                'description': '修改个人信息',
                'icon': 'User',
                'colorClass': 'action-orange',
                'route': '/home/user/profile',
                'permission': 'all'
            },
            {
                'id': 4,
                'title': '系统设置',
                'description': '修改系统配置',
                'icon': 'Setting',
                'colorClass': 'action-purple',
                'route': '/home/system/settings',
                'permission': 'admin'
            }
        ]
        
        # 根据用户角色过滤操作
        filtered_actions = []
        for action in base_actions:
            if action['permission'] == 'all':
                filtered_actions.append(action)
            elif action['permission'] == 'super_admin' and current_role == '超级管理员':
                filtered_actions.append(action)
            elif action['permission'] == 'admin' and current_role in ['超级管理员', '普通管理员']:
                filtered_actions.append(action)
        
        return Response({
            'code': 200,
            'message': '获取快速操作成功',
            'data': filtered_actions
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取快速操作失败: {str(e)}',
            'data': []
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def log_user_activity(request):
    """记录用户活动日志"""
    try:
        if hasattr(request, 'data'):
            # DRF请求
            data = request.data
        else:
            # Django原生请求
            if request.content_type == 'application/json':
                data = json.loads(request.body.decode('utf-8'))
            else:
                data = request.POST
        
        action = data.get('action')
        content = data.get('content')
        
        if not action or not content:
            return Response({
                'code': 400,
                'message': '缺少必要参数',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 获取客户端IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip_address = x_forwarded_for.split(',')[0]
        else:
            ip_address = request.META.get('REMOTE_ADDR')
        
        # 获取用户代理
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        
        # 创建日志记录
        log = SystemLog.objects.create(
            user=request.user,
            action=action,
            content=content,
            ip_address=ip_address,
            user_agent=user_agent
        )
        
        return Response({
            'code': 200,
            'message': '日志记录成功',
            'data': {
                'id': log.id,
                'timestamp': log.created_at.isoformat()
            }
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'记录日志失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)